Tile = Eg.Class.extend({
  init: function(tileset, ratio, tilesize){
    this.tileset = tileset;
    this.tilesize = tilesize;
    this.image = $('<img />').attr('src', tileset).hide();
    $(document.body).append(this.image);
    this.preload = false;
    this.ratio = ratio;
  },
  
  toggle: function(){
    if(!this.preload){
        this.setup();
        this.preload = true;
    }
    
    this.image.toggle();
    this.ele.toggle();
  },
  
  setup: function(){
    this.width = this.ratio * this.image.width();
    this.height = this.ratio * this.image.height();
    this.image.css('width', this.width).css('height', this.height);

    this.cursor = $('<div></div>').addClass('mapCursor').css('width', this.ratio * this.tilesize - 2).css('height', this.ratio * this.tilesize - 2).hide();
    
    var self = this;
    this.ele = $('<div></div>').addClass('tile')
    .css('left', document.body.clientWidth / 2 - this.width / 2)
    .css('top', document.body.clientHeight / 2 - this.height / 2)
    .hide().append(this.image).append(this.cursor);
    this.image.mousemove(function(event){
        self.moveCursor(event);
    });
    
    this.cursor.click( function() {
        self.lastPosition = $(this).position();
        $('#test').text('left:' + self.lastPosition.left + ', top:' + self.lastPosition.top);
        self.toggle();
    });
    $(document.body).append(this.ele);
  },
  
  moveCursor: function(event){
    var left = Math.floor(event.offsetX / this.ratio / this.tilesize) * this.ratio * this.tilesize;
    var top = Math.floor(event.offsetY / this.ratio / this.tilesize) * this.ratio * this.tilesize;
    
    this.cursor.show().css('left', left).css('top', top);
  }
});